#pragma once

#include <vector>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "InetAddr.hpp"
#include "Log.hpp"
#include <mutex>

using namespace logModule;

class Route
{
    bool isExist(const InetAddr& user)
    {
        for (auto& e : _online_users)
        {
            if (e == user)
            {
                return true;
            }
        }

        return false;
    }

    void addUser(const InetAddr& user)
    {
        LOG(LogLevel::DEBUG) << "新增一个用户:> " << user.getStringAddr();
        _online_users.push_back(user);
    }

    bool deleteUser(const InetAddr& user)
    {
        for (auto it = _online_users.begin(); it != _online_users.end(); ++it)
        {
            if (*it == user)
            {
                LOG(LogLevel::DEBUG) << "删除一个在线用户:> " << user.getStringAddr();
                _online_users.erase(it);
                return true;
            }
        }

        return false;
    }

public:

    Route() = default;
    ~Route() = default;

    void messageRoute(int sockfd, const std::string& message, const InetAddr& peer)
    {
        _mutex.lock();

        if (isExist(peer) == false)
        {
            addUser(peer);
        }

        std::string send_message = peer.getStringAddr() + "#" + message;

        for (auto& user : _online_users)
        {
            sendto(sockfd, send_message.c_str(), send_message.size(), 0, (const sockaddr*)&user.getAddr(), sizeof(user.getAddr()));
        }

        if (message == "QUIT")
        {
            deleteUser(peer);
        }

        _mutex.unlock();
    }

private:

    std::vector<InetAddr> _online_users;
    std::mutex _mutex;
};

